package com.canic.dkd.authorization.security;

import com.canic.dkd.authorization.security.Exception.MyAccessDeniedHandler;
import com.canic.dkd.authorization.security.Exception.MyAuthenticationEntryPoint;
import com.canic.dkd.authorization.security.verifyCode.CustomAuthenticationProvider;
import com.canic.dkd.authorization.security.verifyCode.VerifyServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import javax.servlet.http.HttpServletRequest;

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired private AuthenticationSuccessHandler authenticationSuccessHandler;

    @Autowired private AuthenticationFailureHandler authenticationFailureHandler;

    @Autowired private MyAuthenticationEntryPoint myAuthenticationEntryPoint;

    @Autowired private MyAccessDeniedHandler myAccessDeniedHandler;

    @Autowired private SysUserDetailsService sysUserDetailsService;

    @Autowired private AuthenticationDetailsSource<HttpServletRequest, WebAuthenticationDetails> authenticationDetailsSource;

    /* 自己编写的认证逻辑替换系统自带认证 */
    @Autowired private CustomAuthenticationProvider customAuthenticationProvider;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /* 注册自己编写的认证逻辑 */
        auth.authenticationProvider(customAuthenticationProvider);
        auth.userDetailsService(sysUserDetailsService).passwordEncoder(new PasswordEncoder() {
            @Override public String encode(CharSequence charSequence) { return charSequence.toString(); }
            @Override public boolean matches(CharSequence charSequence, String s) { return s.equals(charSequence.toString()); }
        });
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        /* 设置拦截忽略文件夹，可以对静态资源放行 */
        web.ignoring().antMatchers("/css/**", "/js/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .formLogin()
            .loginPage("/login.html")
            .loginProcessingUrl("/auth/login")
            .successHandler(authenticationSuccessHandler)
            .failureHandler(authenticationFailureHandler)
            //.and()
            //.logout()
            //.logoutUrl("/auth/logout")
            //.logoutSuccessUrl("/login.html")
            /* 验证码 */
            .authenticationDetailsSource(authenticationDetailsSource)
            .and()
            .authorizeRequests()
            /* 认证+验权处理 */
            .antMatchers("/login.html", "/getVerifyCode","/favicon.ico").permitAll()
            .anyRequest()
            .access("@rbacService.hasPermission(request, authentication)")
            //.and()
            /* 禁用session 不可放开 */
            //.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .csrf().disable();

        /* 注册自定义异常 */
        http.exceptionHandling().authenticationEntryPoint(myAuthenticationEntryPoint).accessDeniedHandler(myAccessDeniedHandler);
    }

    /**
     * 密码加密
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /**
     * 注入验证码servlet
     */
    @Bean
    public ServletRegistrationBean indexServletRegistration() {
        ServletRegistrationBean registration = new ServletRegistrationBean(new VerifyServlet());
        registration.addUrlMappings("/getVerifyCode");
        return registration;
    }
}
